package cc.bookcloud.tool.ocr.controller;

import cc.bookcloud.tool.ocr.common.JResult;
import cc.bookcloud.tool.ocr.common.SVNLogEntity;
import cc.bookcloud.tool.ocr.common.SVNLogVO;
import cn.hutool.db.Entity;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import cc.bookcloud.tool.ocr.common.sqlite.Sqlite3Client;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Desc: SVN 提交日志处理类
 * @Version: 2.0
 * @Author: John Goo
 * @Date: 2022/06/17 15:17
 **/
@Slf4j
@RestController
@Api(tags = "一体化编译发版辅助小工具", value = "一体化编译发版辅助小工具")
@RequestMapping("/svnlog")
public class SVNLogController {

    @Resource
    private Sqlite3Client sqlite3Client;

    private static final String path = "E:\\svn.log";

    private static final String SEPARATOR = "------------------";

    private static final String PROJECT_PATH_PREFIX = "/src/szjz-cloud-bifrost/branch";

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
    * desc   获取svn列表数据
    * @author oycq
    * @date 2022/9/22
    * @param requestVO:
    * @return JResult<List<SVNLogVO>>
    */
    @PostMapping("/getSVNEntityDataList")
    public JResult<List<SVNLogVO>> getSVNEntityDataList(@RequestBody RequestVO requestVO) throws SQLException {
        JResult<List<SVNLogVO>> result = JResult.build();
        StringBuilder sql = new StringBuilder("select * from SVN_LOG_TABLE");
        if (requestVO != null && !StringUtils.isEmpty(requestVO.getAuthor())) {
            sql.append(" where author like ").append("'%").append(requestVO.getAuthor().trim()).append("%'");
        }
        List<SVNLogEntity> dataList = sqlite3Client.use().query(sql.toString(), SVNLogEntity.class, null);
        List<SVNLogVO> logVOList = new ArrayList<>();
        for (SVNLogEntity entity : dataList) {
            SVNLogVO svnLogVO = new SVNLogVO();
            BeanUtils.copyProperties(entity, svnLogVO);
            String lines = entity.getLines();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<cc.bookcloud.tool.ocr.common.version.LineRecord> list = objectMapper.readValue(lines, new TypeReference<List<LineRecord>>() {
                });
                svnLogVO.setLineList(list);
            } catch (IOException e) {
                e.printStackTrace();
            }
            logVOList.add(svnLogVO);
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate startLocalDate = null;
        LocalDate endLocalDate = null;
        String startDate = requestVO.getStartDate();
        String endDate = requestVO.getEndDate();
        boolean b1 = !StringUtils.isEmpty(startDate);
        if (b1) {
            try {
                startLocalDate = LocalDate.parse(startDate.trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            } catch (Exception e) {
                result.setMsg("开始时间参数格式有误!");
                result.setCode(500);
                return result;
            }
        }
        boolean b2 = !StringUtils.isEmpty(endDate);
        if (b2) {
            try {
                endLocalDate = LocalDate.parse(endDate.trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            } catch (Exception e) {
                result.setMsg("结束时间参数格式有误!");
                result.setCode(500);
                return result;
            }
        }

        LocalDate finalStartLocalDate = startLocalDate;
        LocalDate finalEndLocalDate = endLocalDate;
        if (b1 && b2) {
            logVOList = logVOList.stream().filter(item -> {
                String submitTime = item.getSubmitTime();
                LocalDate localDate = LocalDate.parse(submitTime.trim(), dateTimeFormatter);
                return ( (finalStartLocalDate.isBefore(localDate) || finalEndLocalDate.isEqual(localDate))
                        && (finalEndLocalDate.isAfter(localDate) || finalEndLocalDate.isEqual(localDate)));
            }).collect(Collectors.toList());
        } else if (b1) {
            logVOList = logVOList.stream().filter(item -> {
                String submitTime = item.getSubmitTime();
                LocalDate localDate = LocalDate.parse(submitTime.trim(), dateTimeFormatter);
                return (finalStartLocalDate.isBefore(localDate) || finalStartLocalDate.isEqual(localDate));
            }).collect(Collectors.toList());
        } else if (b2) {
            logVOList = logVOList.stream().filter(item -> {
                String submitTime = item.getSubmitTime();
                LocalDate localDate = LocalDate.parse(submitTime.trim(), dateTimeFormatter);
                return (finalEndLocalDate.isAfter(localDate) || finalEndLocalDate.isEqual(localDate));
            }).collect(Collectors.toList());
        }
        result.setData(logVOList);
        return result;
    }

    @Data
    static class RequestVO {
        private String author;
        private String startDate;
        private String endDate;
    }

    @Data
    static class LineRecord {

        // 修改标志
        private String modifyFlg;
        // fullPath=/src/szjz-cloud-bifrost/branch/zhcz-platform-v2.0.1.1/bifrost-service/bifrost-basic/basic-service/src/main/java/com/szjz/cloud/bifrost/basic/domain/relation/entity/FinancialSupportPersonInfo.java
        // relativePath=bifrost-service/bifrost-basic/basic-service/src/main/java/com/szjz/cloud/bifrost/basic/domain/relation/entity/FinancialSupportPersonInfo.java
        // 代码路径
        //private String codePath;
        // 全路径
        private String fullPath;
        // 相对路径
        private String relativePath;
    }

    /**
    * desc   desc 解析SVN日志接口
    * @author oycq
    * @date 2022/9/22
    * @param multipartFile:
    * @return JResult<List<SVNLogVO>>
    */
    @PostMapping("/convert")
    public JResult<List<SVNLogVO>> convert(@RequestParam("files") MultipartFile multipartFile) throws IOException, SQLException {

        JResult<List<SVNLogVO>> result = JResult.build();
        List<String> segList = new ArrayList<>();
        //按行读取文件
        try (InputStream inputStream = multipartFile.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                segList.add(str);
            }
        }
        List<List<String>> content = new ArrayList<>();
        List<SVNLogEntity> svnLogList = new ArrayList<>();
        List<SVNLogVO> svnLogVOList = new ArrayList<>();
        //按照分割线收集每次Svn提交的数据
        for (int i = 0; i < segList.size(); i++) {
            if (segList.get(i).startsWith(SEPARATOR)) {
                List<String> temp = new ArrayList<>();
                boolean f = false;
                int end = 0;
                for (int j = 0; j < segList.size(); j++) {
                    if (!f) {
                        j = i < segList.size() - 1 ? i + 1 : i;
                        f = true;
                    }
                    if (segList.get(j).startsWith(SEPARATOR)) {
                        end = j;
                        break;
                    }
                }
                int k = i + 1;
                for (; k < end; k++) {
                    String lineContent = segList.get(k);
                    if (!StringUtils.isEmpty(lineContent)) {
                        temp.add(lineContent);
                    }
                }
                if (!CollectionUtils.isEmpty(temp)) {
                    content.add(temp);
                }
                i = k - 1;
            }
        }
        //组装SVN提交日志记录
        for (List<String> record : content) {
            SVNLogEntity svnEntity = new SVNLogEntity();
            SVNLogVO svnLogVO = new SVNLogVO();
            record.forEach(item -> {
                if (item.startsWith("r")) {
                    String[] submitInfo = item.split("\\|");
                    svnEntity.setRevision(submitInfo[0]);
                    svnEntity.setAuthor(submitInfo[1]);
                    String time = submitInfo[2];
                    if (time.contains("+0800")) {
                        time = time.substring(0, time.indexOf("+0800"));
                    }
                    svnEntity.setSubmitTime(time);
                } else if (item.contains(PROJECT_PATH_PREFIX)) {
                    String[] lineRecord = item.trim().split("\\ ");
                    String res = svnEntity.getLines() == null ? "" : svnEntity.getLines();
//                    svnEntity.addLine(lineRecord[0], lineRecord[1]);
                    svnEntity.setLines(res + lineRecord[1]);
                    svnLogVO.addLine(lineRecord[0], lineRecord[1]);
                } else if (!item.contains("改变的路径")) {
                    String str = svnEntity.getRemark() == null ? "" : svnEntity.getRemark();
                    svnEntity.setRemark(str + item);
//                    svnEntity.setRemark(item);
                }
            });
            String entityLines = svnLogVO.transferJson();
            svnEntity.setLines(entityLines);
            svnEntity.setCreateTime(LocalDateTime.now().format(formatter));
            BeanUtils.copyProperties(svnEntity, svnLogVO);
            svnLogList.add(svnEntity);
            svnLogVOList.add(svnLogVO);
        }
        for (SVNLogEntity svnLogEntity : svnLogList) {
            String sql = "select * from SVN_LOG_TABLE where revision = " + "'" + svnLogEntity.getRevision() + "'";
            List<SVNLogEntity> query = sqlite3Client.use().query(sql, SVNLogEntity.class, null);
            if (query.size() == 0) {
                Entity entity = Entity.create("SVN_LOG_TABLE").parseBean(svnLogEntity, false, true);
                sqlite3Client.use().insert(entity);
            }
        }
        result.setData(svnLogVOList);
        return result;
    }


    @PostMapping("/updateSVN")
    public JResult<String> updateSVN(@RequestParam("data") List<String> dataList) {
        for (String codePath : dataList) {
            System.out.println(codePath);
        }
        return null;
    }
}
